<script setup lang="ts">
import Banner from '@/components/Banner.vue';
import { onMounted } from 'vue';
import axios from '@/http/axios';
import { reactive, ref } from 'vue';
import router from '@/router';
import { useLoginStore } from '@/stores/LoginStore';
import { da } from 'element-plus/es/locales.mjs';
import { ElMessage } from 'element-plus';

const loginStore = useLoginStore();

interface Flower {
  flowerId: number;
  use: string;
  name: string;
  price: number;
  material: string;
  category: string;
  count: number;
  image: string;
}
const flowerObject = reactive<{ [key: string]: Flower[] }>({
  loveFlowers: [],      // 爱情鲜花
  birthdayFlowers: [],  // 生日鲜花
  friendFlowers: [],    // 友情鲜花
  businessFlowers: [],    // 商务鲜花
  sickvisitFlowers: [],    // 探病鲜花
  greetingFlowers: []    // 问候鲜花
})
const nav = [
  {
    title: '知名鲜花电商',
    text: '权威认证企业，深受用户喜爱'
  },
  {
    title: '品牌保证 口碑真实',
    text: '累计好评50w+条'
  },
  {
    title: '鲜花实拍秀展示',
    text: '敢展示派送前实拍的鲜花网'
  },
  {
    title: '快至1小时送达',
    text: '全国连锁，实时制作'
  },
  {
    title: '退赔承诺',
    text: '值得信赖的售后服务保障'
  },

]
const flower = ref<Flower>({
  flowerId: 0,
  use: '',
  name: '',
  price: 0,
  material: '',
  category: '',
  count: 0,
  image: ''
})
const dialogVisible = ref(false);
const title = ref(['爱情鲜花', '生日鲜花', '友情鲜花', '商务鲜花', '探病鲜花', '问候鲜花'])
async function getFlowerByUse(use: string): Promise<Flower[]> {
  let res = await axios.get(`/flower/use/${use}`);
  return res.data.data.slice(0, 8);
}
async function getFlowerById(id: number): Promise<Flower> {
  let res = await axios.get(`/flower/id/${id}`);
  // console.log(res.data.data);
  return res.data.data;
}

let userId: number = 0

onMounted(async () => {
  console.log('组件初始化前');
  flowerObject.loveFlowers = await getFlowerByUse('爱情鲜花');
  flowerObject.birthdayFlowers = await getFlowerByUse('生日鲜花');
  flowerObject.friendFlowers = await getFlowerByUse('友情鲜花');
  flowerObject.businessFlowers = await getFlowerByUse('商务鲜花');
  flowerObject.sickvisitFlowers = await getFlowerByUse('探病问候');
  flowerObject.greetingFlowers = await getFlowerByUse('问候长辈');
  const response = await axios.get(`/cart`,{
    headers: {
      'Authorization': loginStore.loginToken
    },
  });
  userId = response.data.userId;
  console.log(userId);
})

// 购买花
async function buyFlower(id: number) {
  dialogVisible.value = true;
  num.value = 1
  // 从后端获取花的详细信息
  flower.value = await getFlowerById(id);
  // console.log(flower.value);
}
const num = ref(1);
function handleChange(val: number) {
  flower.value.count = val;
  // console.log("flower.value.count"+flower.value.count)
  // console.log("num"+num.value)
}

//添加购物车
async function addFlower(flowerId: number, userId: number, count: number) {
  if(loginStore.loginToken == null || loginStore.loginToken=='') {
    ElMessage({
      message:"请先登录",
      type:"warning",
      duration: 2000
    })
    dialogVisible.value = false;
  }else{
  dialogVisible.value = false
  const cart = await axios.get(`/cart/getcart/${userId}/${flowerId}`);
  if (Number(cart.data) != 0) {
    console.log("updata")
    await axios.put(`/cart/updateCount/${userId}/${flowerId}/${count + Number(cart.data)}`);
  } else {
    console.log("add")
    await axios.post(`/cart/addFlower/${userId}/${flowerId}/${count}`);
  }
}
}

// 跳转排序页面
function moveSort(use: string) {
  router.push({ name: 'sort', query: { use: use } })
}

</script>

<template>
  <Banner></Banner>
  <!-- 图片栏 -->
  <div class="nav-img">
    <div v-for="(i, index) in nav" :key="index" class="nav-item">
      <img :src="`/src/assets/images/MainView-image/nav${index + 1}.png`" />
      <div style="font-weight: bold;">{{ i.title }}</div>
      <div style="font-size: 14px;">{{ i.text }}</div>
    </div>
  </div>
  <!-- 花分类 -->
  <div class="mainbody" v-for="([key, flowers], index) in Object.entries(flowerObject)">
    <div class="title">
      <img :src="`/src/assets/images/MainView-image/1000${index + 1}.png`">
      <div style="align-items: end;">
        <a @click="moveSort(flowers[index].use)" style="cursor: pointer;">查看更多 ></a>
      </div>
    </div>
    <div style="display: flex; padding-left:20px; margin-top:-20px;">
      <div class="title-flower">
        <img :src="`/src/assets/images/MainView-image/titleflower${index + 1}.jpg`">
      </div>
      <ul class="ul-flower">
        <li class="li-flower" v-for="flower in flowers" @click="buyFlower(flower.flowerId)">
          <img :src="flower.image">
          <div class="flower-name">{{ flower.name }}</div>
          <div class="flower-price">￥{{ flower.price }}</div>
        </li>
      </ul>
    </div>
  </div>
  <!-- 花信息弹窗 -->
  <el-dialog v-model="dialogVisible">
    <div class="dialog-content">
      <img :src="`${flower.image}`" class="dialog-image">
      <div>
        <div style="font-size: 20px; font-weight: bold;">{{ flower.name }}</div>
        <hr>
        <div>种类：{{ flower.material }}</div>
        <div>类别：{{ flower.category }}</div>
        <div class="flower-info">
          <div>价格：</div>
          <div style="font-size: 18px; color:red">￥{{ flower.price }}</div>
        </div>
      </div>
    </div>
    <div>
      <el-input-number v-model="num" :min="1" @change="handleChange" class="input-number" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <!-- userid待获取，暂为死数据 -->
        <el-button type="primary" @click="addFlower(flower.flowerId, userId, Number(num))">
          加入购物车
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped>
.nav-img {
  display: flex;
  width: 80%;
  margin: 10px auto;
  justify-content: space-between;
  text-align: center;
}

.nav-item {
  flex: 1;
  background-color: #fff;
}

.mainbody {
  /* border: 1px solid red; */
  width: 80%;
  height: 700px;
  margin: 10px auto;
}

.title {
  display: flex;
  width: 93%;
  margin: 20px 0 0 20px;
  justify-content: space-between;
}

.title a {
  text-decoration: none;
  font-size: 14px;
  color: #000;
}

.title a:hover {
  color: rgb(158, 64, 26);
}

.title-flower {
  /* border:1px yellow solid; */
  flex: 1;
  height: 600px;
  width: 250px;
  margin-top: 20px;
  text-align: center;
  padding-top: 10px;
}

.title-flower img {
  width: 98%;
  height: 98%;
}

.title-flower img:hover {
  transform: scale(1.05);
}

.ul-flower {
  flex: 5;
  display: flex;
  flex-wrap: wrap;
  padding-left: 10px;
}

.li-flower {
  width: 220px;
  height: 300px;
  /* border:1px solid green; */
  list-style: none;
  margin: 5px;
  background-color: #fff;
}

.li-flower:hover {
  transform: scale(1.05);
  cursor: pointer;
}

.li-flower img {
  display: block;
  width: 200px;
  height: 200px;
  margin: 10px auto;
}

.flower-name {
  font-size: 14px;
  width: 200px;
  margin: 10px auto;
}

.flower-price {
  font-size: 20px;
  font-weight: bold;
  color: red;
  width: 200px;
  margin-left: 10px;
}

.dialog-content {
  display: flex;
  width: 70%;
  margin: 0 auto;
}

.dialog-image {
  width: 200px;
  height: 200px;
  margin: 0 20px 20px 0;
}

.flower-info {
  display: flex;
  line-height: 30px;
}

.input-number {
  transition: fixed;
  left: 330px;
}
</style>